<template>
  <div v-if="aid">
    <el-alert
      class="mb-4"
      description="当前为默认的SQL更新语句，在版本列表中，进行版本比对后，点击合并更新，可以把这个合并到一起，解决低版本用户的SQL更新问题"
      title="说明"
      type="error"
    />
    <div v-loading="loading">
      <Codemirror v-model:value="code" :options="cmOptions" height="400px" />
    </div>
    <div v-if="sql.edit" class="text-center text-sm text-gray-500 mt-2">当前SQL脚本已被修改</div>
    <div class="text-center mt-5">
      <el-button type="primary" @click="handleSaveUpgradeSql()">保存当前SQL</el-button>
      <el-button type="danger" @click="downInstallSql()">下载upgrade.sql</el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { getUpgradeSql, saveUpgradeSql } from '@/api/addons/addon'

defineOptions({
  name: 'UpgradeSqlEdit'
})

const props = defineProps<{
  aid: number | string
}>()

const emit = defineEmits<{
  success: []
}>()

const sql = ref<any>({})
const code = ref('')
const loading = ref(true)

const cmOptions = {
  tabSize: 4,
  mode: 'text/x-mysql',
  theme: 'monokai',
  lineNumbers: true,
  line: true
}

const handleSaveUpgradeSql = () => {
  // 执行前提示
  saveUpgradeSql(props.aid, code.value).then((res) => {
    ElMessage.success('保存成功')
    sql.value = res.data
    emit('success')
  })
}

const handleGetUpgradeSql = () => {
  getUpgradeSql(props.aid)
    .then((res) => {
      sql.value = res.data
      code.value = res.data.sql || '\n'
      loading.value = false
    })
    .catch(() => {
      loading.value = false
      sql.value = {}
      code.value = ''
    })
}

const downInstallSql = () => {
  // 点击后下载为sql文件
  const blob = new Blob([code.value], { type: 'text/plain;charset=utf-8' })
  const downloadLink = document.createElement('a')
  downloadLink.href = window.URL.createObjectURL(blob)
  downloadLink.download = 'upgrade.sql'
  document.body.appendChild(downloadLink)
  downloadLink.click()
  document.body.removeChild(downloadLink)
}

onMounted(() => {
  handleGetUpgradeSql()
})
</script>

<style scoped>
/* UnoCSS 已经提供了所需的样式，这里可以添加自定义样式 */
</style>
